﻿#include <iostream>

using namespace std;

template <class T>
class my_shared
{
private:
    T *pData;
    int *count;//利用指针同步修改

public:
    my_shared()//等待其他对象赋值
    {
        pData=NULL;
        count=NULL;
    }

    my_shared(T *pData):count(new int(0))//定义并初始化
    {
        if(pData!=NULL)
        {
            this->pData=pData;
            (*count)++;
        }
    }

    my_shared(my_shared<T> & ptr):pData(ptr.pData),count(ptr.count)//拷贝构造函数
    {
        if(pData!=NULL)
        {
            (*count)++;
        }

    }

    void operator =(const my_shared<T> &ptr)//指向新数据
    {
        if(this->pData==NULL)//还没有定义
        {
            this->pData=ptr.pData;
            this->count=ptr.count;
            if(this->pData)
            {
                (*this->count)++;
            }
        }//重新指向,这里默认自己不给自己赋值
        else
        {
            if(this->pData!=ptr.pData)//不指向同一个
            {
                (*count)--;
                if((*count)==0)
                {
                    delete this->pData;
                }
                this->pData=ptr.pData;
                this->count=ptr.count;
                if(this->pData)
                {
                    (*this->count)++;
                }
            }
        }
    }

    void reset()
    {
        (*count)--;
        if(!(*count))
        {
            delete pData;
        }
        count =new int(0);//缺陷调用reset然后重新指向的count空间被浪费
        pData=NULL;
    }

    int use_count()
    {
        return *count;
    }

};

int main()
{
    my_shared<int> p1(new int(10));
    cout << p1.use_count()<<endl;

    my_shared<int> p2=p1;
    cout << p2.use_count()<<endl;
    cout << p1.use_count()<<endl;

    my_shared<int> p3(new int(10));
    p2=p3;
    cout << p1.use_count()<<endl;
    cout << p2.use_count()<<endl;
    cout << p3.use_count()<<endl;
    /*
    p3.reset();
    cout << p3.use_count()<<endl;
    cout << p2.use_count()<<endl;
    */
    my_shared<int> p4;
    p4=p3;
    cout << p3.use_count()<<endl;
    cout << p4.use_count()<<endl;
    p3=p4;
    cout << p3.use_count()<<endl;
    cout << p4.use_count()<<endl;
    return 0;
}
